import { SETCARTLIST } from '../mutation-type'
import { post } from '@/utils/axios'
const module = {
  namespaced: true, // 命名空间
  state: {
    cartList: []
  },
  actions: {
    getCartListAction(context, payload) {
      post({
        url: '/hybrid/uni/cart'
      }).then(res => {
        const { result, status } = res
        if (status >= 0) {
          context.commit('SETCARTLIST', result)
        }
      })
    },
    deleteSelectCart(context, payload) {
      post({
        url: '/hybrid/uni/cart-deleteall',
        data: payload
      }).then(res => {
        context.dispatch('getCartListAction')
      })
    }
  },
  mutations: {
    [SETCARTLIST](state, payload) {
      state.cartList = payload
    }
  },
  getters: {
    cartNum(state, getters, rootState, rootGetters) { // 属性
      let num = 0;
      if (state.cartList) {
        let aNum = state.cartList.map(item => {
          return item.selectedNum
        });
        // console.log(aNum)
        aNum.forEach(element => {
          num += (element * 1)
        });
      }
      return num
    },
    cartListOfType: (state, getters, rootState, rootGetters) => (type) => {
      if (state.cartList.length <= 0) return []
      return state.cartList.filter(item => item.type === type)
    }
  }
}

export default module
